// state
const state = {
  userInfo: null,
  token: null
}

// getters
const getters = {
  isAuthenticated: (state) => !!state.token,
  getUserInfo: (state) => state.userInfo
}

// mutations
const mutations = {
  SET_TOKEN(state, token) { state.token = token },
  SET_USER(state, info) { state.userInfo = info }
}

// actions
const actions = {
  // 登录
  login({ commit }, role) {
    // 模拟登录，直接设置用户信息
    const userInfo = {
      UserName: role === 'expert' ? '专家用户' : role === 'bidder' ? '投标人' : '管理员',
      Role: role
    }
    commit('SET_USER', userInfo)
    commit('SET_TOKEN', 'demo-token')
  },

  // 登出
  logout({ commit }) {
    commit('SET_USER', null)
    commit('SET_TOKEN', null)
  }
}

export default { namespaced: true, state, getters, mutations, actions }

/**
 * 检查是否有token
 */
export const hasToken = () => {
  return !!localStorage.getItem('token');
};

/**
 * 获取token
 */
export const getToken = () => {
  return localStorage.getItem('token');
};

/**
 * 设置token
 */
export const setToken = (token) => {
  localStorage.setItem('token', token);
};

/**
 * 移除token
 */
export const removeToken = () => {
  localStorage.removeItem('token');
};
